package com.android.svmc.app.mobile.data;

import java.util.HashMap;

import com.android.svmc.app.mobile.util.CommonDefine;

import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.widget.BaseAdapter;
import android.widget.ImageView;

public class DownloadIMG implements Runnable, CommonDefine {

	private int IMAGE_DOWNLOADED = 1;
	private String imgUrl;
	private ImageView imageView;
	private HashMap<String, Bitmap> hashMap = DataManager.hashMapBitmap;
	private boolean checkAdapter = false;

	public DownloadIMG(String ImgUrl) {
		this.imgUrl = ImgUrl;
	}

	BaseAdapter adapter = null;

	public void Start(ImageView imageView, BaseAdapter adapter) {
		if (adapter != null)
			checkAdapter = true;
		this.imageView = imageView;
		if (hashMap.containsKey(imgUrl)) {
			Bitmap bitmap = hashMap.get(imgUrl);
			imageView.setImageBitmap(bitmap);
			imageView.invalidate();
		} else {
			this.adapter = adapter;
			Thread thread = new Thread(this);
			thread.start();
		}
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			Bitmap bitmap = DataManager.GetBitmap(imgUrl);
			Message msg = new Message();
			msg.obj = bitmap;
			msg.what = IMAGE_DOWNLOADED;
			threadHandler.sendMessage(msg);
		} catch (NullPointerException e) {
			e.printStackTrace();
		}
		

	}

	private Handler threadHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == IMAGE_DOWNLOADED) {
				Bitmap bm = (Bitmap)msg.obj;
				imageView.setImageBitmap(bm);
				imageView.invalidate();
				if (checkAdapter)
					adapter.notifyDataSetChanged();
			}
		}
	};

}
